import json
import random
import time
from hashlib import md5
from time import sleep

import requests
from PIL import Image
from selenium import webdriver

from selenium.webdriver import ActionChains


# 访问dx--图片验证码方法
driver = webdriver.Chrome()


def save_img(driver):
    driver.save_screenshot('page.png')  # 截图
    code_img_ele = driver.find_element_by_xpath('//*[@class="verify_header"]/img')  # 要验证的图片验证码
    location = code_img_ele.location  # 验证码左上角的坐标x,y
    size = code_img_ele.size  # 验证码对应的长和宽
    # 得到左上角和右下角的坐标
    # left, top, right, height

    rangle = (
        int(location['x']), int(location['y']), int((location['x'] + size['width'])),
        int((location['y'] + size['height']))
    )
    # print(rangle)
    image1 = Image.open('./page.png')
    # code_img_name = './code.png'
    # crop根据rangle元组内的坐标进行裁剪 裁剪出验证码区域
    frame = image1.crop((rangle))
    frame.save('./code.png')
    return code_img_ele




def parse_data(result):
    print(result)
    node_list = []  # 存储即将被点击的点的坐标  [[x1,y1],[x2,y2]]
    if '|' in result:
        nums = result.split('|')
        for i in range(len(nums)):
            x = int(nums[i].split(',')[0])
            y = int(nums[i].split(',')[1])
            xy_list = [x, y]
            node_list.append(xy_list)
        print('node_list---有几个要验证的',len(node_list), '分别要验证的坐标系是',node_list)
    else:
        x = int(result.split(',')[0])
        y = int(result.split(',')[1])
        xy_list = [x, y]
        node_list.append(xy_list)

    return node_list


def click_codeImg(all_list, code_img_ele):
    # code_img_ele 验证码的图 、all_list要被点击的坐标
    # 遍历列表，使用动作链对每一个列表元素对应的x,y指定的位置进行点击操作
    for item in all_list:
        x = item[0] * 1.6
        y = item[1] * 1.6
        # x = item[0]
        # y = item[1]
        # move_to_element_with_offset移动到距某个元素（左上角坐标）多少距离的位置
        ActionChains(driver).move_to_element_with_offset(code_img_ele, x, y).click().perform()
        time.sleep(5)
        print('点击成功')
    time.sleep(2)
    # 完成动作链点击操作后，定位确认按钮并点击
    driver.find_element_by_xpath("//*[text()='确认']").click()
    driver.find_element_by_xpath("//*[text()='查询']")


def login():
    driver.get('https://dxt.yayi360.com/#/')
    driver.maximize_window()
    driver.find_element_by_xpath("//div[@placeholder='请输入手机号']/input").send_keys("13212121212")
    driver.find_element_by_xpath("//div[@placeholder='请输入密码']/input").send_keys("123123")
    driver.find_element_by_class_name("zh_postForm").click()
    # sleep(random.random() * 3)
    try:
        driver.find_element_by_xpath('//*[text()="登录成功"]')
        time.sleep(2)
        driver.quit()
        print('zai')
    except:
        time.sleep(5)
        print("b不在")
        try:
            # 保存页面截图，并根据坐标裁剪获取验证码图片
            code_img_ele = save_img()

        except Exception as e:
            driver.quit()
            raise e


login()
